#include <iostream>
#include "Sock.hpp"
#include "Protocol.hpp"

using namespace ns_protocol;

void Usage(const std::string &proc)
{
    std::cout << "\nUsage: " << proc << " ServerPort ServerIP\n"
              << std::endl;
}

int main(int argc, char *argv[])
{

    if (argc != 3)
    {
        Usage(argv[0]);
        exit(-1);
    }
    uint16_t port = atoi(argv[2]);
    std::string ip = argv[1];
    Sock sock;
    int s = sock.Socket(); // 建立套接字
    if (!sock.Connect(s, ip, port))
    {
        std::cerr << " Connect failed " << std::endl;
        exit(2);
    }

    std::string inbuffer;
    bool quit = false;
    while (!quit)
    {
        // 1.获取需求
        Request req;
        std::cout << "Please Enter->" << std::endl;
        std::cin >> req._x >> req._op >> req._y;
        // 序列化
        std::string str = req.Serialize();
        // 添加长度报头
        str = Encode(str);
        // 发送给服务端
        Send(s, str);
        while (true)
        {
            // 正常读取
            bool r = Recv(s, &inbuffer);
            // 读取失败，退出循环
            if (!r)
            {
                quit = true;
                break;
            }
            // 解析报头
            std::string s = Decond(inbuffer);
            // 保证是一个完整的报文
            if (s.empty())
                continue;
            Response resp;
            // 反序列化
            resp.Deserialize(s);
            std::string err;
            switch (resp._code)
            {
            case 1:
                err = "除0错误";
                break;
            case 2:
                err = "模0错误";
                break;
            case 3:
                err = "非法操作";
                break;
            default:
                std::cout << req._x << req._op << req._y << " = " << resp._result << " [success]" << std::endl;
                break;
            }
            if(!err.empty()) std::cerr << err << std::endl;

            // sleep(1);
            break;//一次处理一个报文，所以要break
        }
    }
    close(s);
    return 0;
}